<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<title>vue2.x</title>
</head>

<body>
	<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
	<script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
	<script src="https://cdn.jsdelivr.net/npm/lodash@4.13.1/lodash.min.js"></script>
	
	<div id="app">
		<span>
			<p>
				Ask a yes/no question:<input v-model="question">
			</p>
			<p>{{ answer }}</p>
		</span>
		<hr/>
	</div>
	<script>
		var app = new Vue({
			el: '#app',
			data: {
				question: '',
				answer: 'I cannot give you an answer until you ask a question!'
			},
			methods: {
				getAnswer: function () {
					if (this.question.indexOf('?') === -1) {
						this.answer = 'Questions usually contain a question mark. ;-)'
						return
					}
					this.answer = 'Thinking...'
					var vm = this
					axios.get('https://yesno.wtf/api')
						.then(function (response) {
							vm.answer = _.capitalize(response.data.answer)
						})
						.catch(function (error) {
							vm.answer = 'Error! Could not reach the API. ' + error
						})
				}
			},
			created: function () {
				// `_.debounce` 是一个通过 Lodash 限制操作频率的函数
				this.debouncedGetAnswer = _.debounce(this.getAnswer, 500)
			},
			watch: {
				// 如果 `question` 发生改变，这个函数就会运行
				question: function (newQuestion, oldQuestion) {
					this.answer = 'Waiting for you to stop typing...'
					this.debouncedGetAnswer()
				}
			}
		})
	</script>
</body>

</html>